package com.huxiu.yd.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

import com.huxiu.yd.R;
import com.huxiu.yd.utils.Constants;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IWXAPI mWeixinShareApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_KEY, false);
        mWeixinShareApi.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        int result;
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (baseResp instanceof SendAuth.Resp) {
                    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
                    Intent intent = new Intent(Constants.ACTION_WECHAT_LOGIN);
                    intent.putExtra("result", baseResp.errCode == BaseResp.ErrCode.ERR_OK);
                    Log.d("result", " " + (baseResp.errCode == BaseResp.ErrCode.ERR_OK));
                    Log.d("code", ((SendAuth.Resp) baseResp).code);
                    intent.putExtra("code", ((SendAuth.Resp) baseResp).code);
                    lbm.sendBroadcast(intent);
                    finish();
                }
                result = R.string.errcode_success;
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = R.string.errcode_cancel;
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = R.string.errcode_deny;
                break;
            default:
                result = R.string.errcode_unknown;
                break;
        }

        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
        finish();
    }

}
